import 'package:app/api/container/index.dart';
import 'package:app/components/index.dart';
import 'package:app/util/StringUtils.dart';
import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;


/// 空托回收
class ContainerRecovery extends StatefulWidget{
  const ContainerRecovery({super.key});
  @override
  State<ContainerRecovery> createState() => _ContainerRecoveryState();
}

class _ContainerRecoveryState extends State<ContainerRecovery>{

  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  final FocusNode _firstFocusNode = FocusNode();

  final FocusNode _containerFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    // 在初始化时将焦点放在第一个文本框上
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _firstFocusNode.dispose();
  }

  //任务号
  String _code = "";

  // 托盘编号
  String _containerCode = "";

  List<String> _containers = [];

  submit(){
    Forms.validate(_formKey!).then((valid){
      if(valid){
        if(_containers.isEmpty){
          Error.of(context).show('请扫描要回收的托盘');
          return;
        }
        Confirm.of(context).show('确认是否空托，并回收', ()=>{
          ContainerApi.of(context).recovery({'station': _code, 'containers': _containers}).then((res){
            Navigator.pop(context);
            if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)){
              clear();
              Success.of(context).show('空托呼叫成功，请等待');
            }
          })
        });
      }
    });
  }

  void clear(){
    setState(() {
      _code = "";
      _containerCode = "";
      _containers = [];
    });
  }

  void scan(String key) async{
    String? qrCode = await scanner.scan();
    if (key == 'containerCode') {
      setState(() => _containerCode = qrCode.toString());
    } else if (key == 'code') {
      setState(() => _code = qrCode.toString());
    }
  }

  void setValue(String key, String value){
    switch(key){
      case '_code' : setState(() => _code = value); FocusScope.of(context).requestFocus(_containerFocusNode); break;
      case '_containerCode' : setState(() => _containerCode = value); break;
      default:
        throw Exception("key error");
    }
  }

  void changeValue(String key, String value){
    switch(key){
      case '_code' : _code = value; break;
      default:
        throw Exception("key error");
    }
  }

  void hideKeyBorder(){
    FocusScopeNode currentFocus = FocusScope.of(context);
    if(!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null){
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  /// 添加托盘
  void addContainer(value){
    setState(() {
      if(!_containers.contains(value) && StringUtils.isNotNull(value)){
        _containers.add(value);
        FocusScope.of(context).requestFocus(_containerFocusNode);
      }
      _containerCode = "";
    });
  }

  /// 获取树形元素
  List<TreeItem> getTreeItem(){
    return _containers.map((item) => TreeItem(
        label: item,
        expand: false,
        buttons: [
          TreeItemButton(
              label: '删除',
              onPressed: remove,
              backgroundColor: Colors.red,
              isShow: true
          ),
        ],
    )).toList();
  }

  /// 删除
  void remove(index, childIndex, leave){
    Confirm.of(context).show('确定要删除托盘么？', (){
      setState(() => _containers.remove(_containers[index]));
      Navigator.pop(context);
    });
  }

  void onCheck(bool checked, int index, int childIndex, int level){

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '空托回收'),
      body: GestureDetector(
        onTap: hideKeyBorder,
        child: Container(
          color: const Color.fromARGB(255, 245, 245, 245),
          child: Column(
            children: [
              Group(
                // title: '站点码',
                context: context,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Forms(
                      formKey: _formKey,
                      formItem: [
                        FormItem(
                          type: 'input',
                          labelText: '站  点  码',
                          placeholder: '请扫描站点码',
                          labelWidth: 100,
                          focusNode: _firstFocusNode,
                          filedName: 'code',
                          icon: const Icon(Icons.qr_code_scanner_rounded),
                          value: _code,
                          onChange: (value) => changeValue('_code', value),
                          onEntry: (value) => setValue('_code', value),
                          iconOnTap: () => scan('code'),
                          rules: const {'code': [{'required': true, 'message': '站点码不能为空'}]},
                        ),
                        FormItem(
                          type: 'input',
                          focusNode: _containerFocusNode,
                          labelText: '托盘编号',
                          placeholder: '请扫托盘编号',
                          labelWidth: 100,
                          filedName: 'container',
                          icon: const Icon(Icons.qr_code_scanner_rounded),
                          value: _containerCode,
                          onEntry: addContainer,
                          iconOnTap: () => scan('containerCode'),
                          onChange: (value) => setState(() {
                            setValue('_containerCode', value);
                          }),
                        )
                      ],
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 10, right: 10),
                      child: Button(
                        label: '清除',
                        icon: Icons.delete_forever,
                        onPressed: clear,
                        fontColor: Colors.black,
                        backgroundColor: Colors.white,
                        borderColor: const Color.fromARGB(255, 133, 133, 133),
                      ),
                    )
                  ],
                ),
              ),
              Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(top: 10),
                    child:  Tree(
                        onCheck: onCheck,
                        items: getTreeItem()
                    ),
                  ),
              ),
              SizedBox(
                width: MediaQuery.of(context).size.width,
                child: Padding(
                  padding: const EdgeInsets.only(top: 50, left: 20, right: 20),
                  child: Button(
                    onPressed: submit,
                    label: '确认回收',
                    height: 60,
                    fontSize: 18,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}